import { StyleSheet, Text, View, FlatList, Image } from 'react-native';
import React, { useState, useCallback } from 'react';
import { useRoute, useFocusEffect } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { NavBarHeader, ContentStatus } from '~/components';
import { courseHistoryApi } from '~/api/deviceApi';
import { onePx, px2dp, scale } from '~/utils/px2dp';
import { formatTimestamp } from '~/utils/formatDate';
import { appStore } from '~/store';

export default function CourseHistory() {
    const { t } = useTranslation();
    const router = useRoute<any>();
    const { device_sn } = router.params;
    const [listData, setListData] = useState<any>([]);
    const [page, setPage] = useState(1);
    const [loading, setLoading] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const getData = async (pageNumber = 1, isRefreshing = false) => {
        if (loading) return;
        setLoading(true);
        try {
            const res = await courseHistoryApi({ page: pageNumber, pageSize: 10, deviceSn: device_sn });
            const result = res.returnData.list;
            if (isRefreshing) {
                setListData(result);
            } else {
                setListData((prevData) => [...prevData, ...result]);
            }
            if (result.length === 0 || result.length < 10) {
                setHasMore(false);
            } else {
                setHasMore(true);
            }
        } catch (error) {
        } finally {
            setLoading(false);
            setIsRefreshing(false);
        }
    };
    const renderItem = ({ item }) => (
        <View style={[styles.list]}>
            <View style={[styles.row]}>
                <Image source={{ uri: item.courseImg }} style={styles.cover} />
                <View style={{ marginLeft: px2dp(32) }}>
                    <Text style={styles.course_name}>{item.courseName}</Text>
                    <Text style={styles.creat_time}>{formatTimestamp(item.addTime, 1)}</Text>
                    <Text style={styles.t1}>
                        {item.type == 1
                            ? t('CourseHistory.t1')
                            : item.type == 2
                            ? t('CourseHistory.t2')
                            : item.type == 3
                            ? `${item.info}${t('CourseHistory.t3')}${
                                  appStore.app.language == 'zh'
                                      ? item.courseName
                                      : item.enCourseName
                                      ? item.enCourseName
                                      : item.courseName
                              }`
                            : t('CourseHistory.t4')}
                    </Text>
                </View>
            </View>
        </View>
    );
    const handleRefresh = () => {
        setIsRefreshing(true);
        setPage(1);
        getData(1, true);
    };
    // 处理滚动到底部时加载更多
    const loadMore = () => {
        if (!loading && hasMore) {
            const nextPage = page + 1;
            setPage(nextPage);
            getData(nextPage);
        }
    };
    const ListEmptyComponent = () => {
        return <ContentStatus status="empty" />;
    };

    useFocusEffect(
        useCallback(() => {
            getData(1);
        }, []),
    );
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('CourseHistory.title')} />
            <FlatList
                contentContainerStyle={styles.contentContainerStyle}
                showsVerticalScrollIndicator={false}
                data={listData}
                renderItem={renderItem}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={loadMore}
                onEndReachedThreshold={0.1}
                refreshing={isRefreshing}
                onRefresh={handleRefresh}
                ListEmptyComponent={ListEmptyComponent}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },

    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '40%',
    },
    list: {
        backgroundColor: '#fff',
        borderWidth: onePx,
        borderColor: '#eee',
        padding: px2dp(24),
        marginHorizontal: px2dp(32),
        marginTop: px2dp(24),
        borderRadius: px2dp(16),
        flexDirection: 'row',
        alignItems: 'flex-start',
    },
    cover: {
        width: px2dp(80),
        height: px2dp(80),
    },
    creat_time: {
        fontSize: scale(24),
        color: '#a4a4a4',
        marginTop: px2dp(12),
    },
    course_name: {
        fontSize: scale(28),
        fontWeight: 'bold',
    },
    t1: {
        marginTop: px2dp(12),
        fontSize: scale(24),
        color: '#a4a4a4',
    },
});
